package com.jeeplus.modules.sys.utils;

import com.jeeplus.modules.iim.entity.MailPage;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author Administrator
 * @title: SignUtil
 * @projectName JeePlus
 * @description: TODO
 * @date 2019/9/2221:34
 */

public class SignUtil {
    // 与接口配置信息中的Token要一致
    private static String token = "weixinCourse";
    public static void main(String[] args) throws Exception {
        String nonce=getNonceStr(16);
        String time=getTimestamp();
        String tick = "LIKLckvwlJT9cWIhEQTwfN3C81AlAbHXAjWAWvHOzcWfgsBnmymfYziNOhoke68bQ-QeV6d6Fc5-bhyaU_smJA";
        String str = MessageFormat.format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url=http://k26894v027.wicp.vip/jeeplus_war/api/WXWork/index", tick, nonce, time);
        System.out.println(shaEncode(str));
        System.out.println(nonce);
        System.out.println(time);
    }
    public static Map<String,Object> GenerateSignature(String url,String tick) {
        Map<String,Object> map=new HashMap<>();
        try {
            String nonce=getNonceStr(16);
            String time=getTimestamp();
            //String tick = "LIKLckvwlJT9cWIhEQTwfN3C81AlAbHXAjWAWvHOzcWfgsBnmymfYziNOhoke68bQ-QeV6d6Fc5-bhyaU_smJA";
            String str = MessageFormat.format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", tick, nonce, time,url);
            map.put("nonce",nonce);
            map.put("time",time);
            map.put("signature",shaEncode(str));
            map.put("url",url);
            map.put("tick",tick);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
    /***
     * 生成时间戳
     *
     * @Author LH
     * @Description //TODO
     * @Date 12:03 2019/9/26
     * @param
     * @return java.lang.String
     **/
    public static String getTimestamp() {
        //生成时间戳

        long timestampLong = System.currentTimeMillis();

        String timestampStr = String.valueOf(timestampLong);

        return timestampStr;
    }
    /*
    获取签名
     */
    public static String getJsSdkSign(String noncestr, String tsapiTicket, String timestamp, String url) {
        String content = "jsapi_ticket=" + tsapiTicket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
        String ciphertext = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            ciphertext = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return ciphertext;
    }

    /**
     * 验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{token, timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        content = null;
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }
    /***
     * 获取签名随机数
     *
     * @Author LH
     * @Description //TODO
     * @Date 12:04 2019/9/26
     * @param length
     * @return java.lang.String
     **/
    public static String getNonceStr(int length) {

        //生成随机字符串

        String str = "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890";

        Random random = new Random();

        StringBuffer randomStr = new StringBuffer();

        // 设置生成字符串的长度，用于循环

        for (int i = 0; i < length; ++i) {
            //从62个的数字或字母中选择

            int number = random.nextInt(62);

            //将产生的数字通过length次承载到sb中

            randomStr.append(str.charAt(number));
        }

        //将承载的字符转换成字符串

        return randomStr.toString();
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }
    /***
     * 生成签名
     *
     * @Author LH
     * @Description //TODO
     * @Date 12:04 2019/9/26
     * @param inStr
     * @return java.lang.String
     **/
    public static String shaEncode(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}
